<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="40%"
        :before-close="handleClose">
        <el-form v-if="dialogVisible" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px"
            class="demo-ruleForm">
            <el-form-item label="任务模板名称" prop="taskTemplateName">
                <el-input v-model="ruleForm.taskTemplateName" class="w100p" placeholder="请输入任务模板名称"></el-input>
            </el-form-item>
            <el-form-item label="关联计划" prop="workPlanId">
                <el-select :disabled="addEditFlag == 'edit'" v-model="ruleForm.workPlanId" class="w100p" clearable
                    filterable placeholder="请选择计划" @change="handleChangePlan">
                    <el-option :disabled="disableTime(item.endTime)" v-for="item, index in planList" :key="index"
                        :label="`${item.workPlanName}（计划结束时间：${item.endTime}）`" :value="item.workPlanId"></el-option>
                </el-select>
                <span v-if="addEditFlag == 'add' && ruleForm.workPlanId" class="errText">{{ warningText }}</span>
            </el-form-item>
            <template v-if="ruleForm.workPlanId">
                <el-form-item label="任务间隔天数" :prop="addEditFlag == 'add' ? 'intervalDay' : ''">
                    <el-input :disabled="addEditFlag == 'edit'" type="number" v-model="ruleForm.intervalDay"
                        placeholder="请输入天数" @change="handleChangeIntervalDay">
                        <template slot="append">天</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="任务生成时间" prop="generationTime">
                    <el-time-select :disabled="addEditFlag == 'edit'" class="w100p" v-model="ruleForm.generationTime"
                        :picker-options="{
        start: '08:30',
        step: '00:15',
        end: '18:30'
    }" placeholder="选择时间">
                    </el-time-select>
                </el-form-item>
                <el-form-item label="任务有效时间" prop="taskTemplateTime">
                    <el-date-picker :disabled="addEditFlag == 'edit'" v-model="ruleForm.taskTemplateTime"
                        type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions"
                        range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" align="right">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="任务执行时间" prop="executionStartDay">
                    <el-row>
                        <el-col class="elRow" :span="4">
                            <el-form-item class="noLabel" ref="resetDays" prop="executionStartDay">
                                <el-select v-if="resetDays" :disabled="addEditFlag == 'edit'"
                                    v-model="ruleForm.executionStartDay" class="w100p" clearable filterable
                                    placeholder="请选择任务开始天数" @change="handChangeDays">
                                    <el-option :disabled="Number(ruleForm.executionEndDay) < Number(index + 1)"
                                        v-for="day, index in Number(ruleForm.intervalDay || 0)" :key="index"
                                        :label="`第${index + 1}天`" :value="index + 1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item class="noLabel" prop="executionStartTime">
                                <el-time-select :disabled="addEditFlag == 'edit'" v-model="ruleForm.executionStartTime"
                                    class="w100p" @change="handleChangeTime('executionStartTime')" :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '23:45'
    }" placeholder="选择时间">
                                </el-time-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <div class="textCenter">至</div>
                        </el-col>
                        <el-col class="elRow" :span="4">
                            <el-form-item class="noLabel" ref="resetDays" prop="executionEndDay">
                                <el-select v-if="resetDays" :disabled="addEditFlag == 'edit'"
                                    v-model="ruleForm.executionEndDay" class="w100p" clearable filterable
                                    placeholder="请选择任务结束天数" @change="handChangeDays">
                                    <el-option :disabled="Number(ruleForm.executionStartDay) > Number(index + 1)"
                                        v-for="day, index in Number(ruleForm.intervalDay || 0)" :key="index"
                                        :label="`第${index + 1}天`" :value="index + 1"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item class="noLabel" prop="executionEndTime">
                                <el-time-select :disabled="addEditFlag == 'edit'" v-model="ruleForm.executionEndTime"
                                    class="w100p" @change="handleChangeTime('executionEndTime')" :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '23:45'
    }" placeholder="选择时间">
                                </el-time-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form-item>
            </template>
            <el-form-item>
                <div class="line w100p"></div>
            </el-form-item>
            <el-form-item label="作业类型" prop="workType">
                <el-select v-model="ruleForm.workType" class="w100p" clearable filterable placeholder="请选择作业类型">
                    <el-option v-for="item, index in workTypeList" :key="index" :label="item.name"
                        :value="item.key"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="养殖设施" prop="facilityId">
                <el-select v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施" @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次(已封塘)" prop="batchId">
                <el-select v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
            </el-form-item>
            <el-row v-if="ruleForm.workType == 'FEEDING'" :gutter="10"
                v-for="item, index in ruleForm.taskTemplateDetailList" :key="index">
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '投入物料名称' : ''"
                        :prop="`taskTemplateDetailList[${index}][materialNo]`" :rules="rules.materialNo">
                        <el-select clearable filterable class=" w100p" v-model="item.materialNo" placeholder="请选择药品">
                            <el-option v-for="item, index in materialList" :key="index" :label="item.materialName"
                                :value="item.materialNo"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '投入数量' : ''" :prop="`taskTemplateDetailList[${index}][num]`"
                        :rules="rules.num">
                        <el-input type="number" v-model="item.num" placeholder="请输入参数">
                            <template slot="append">
                                <span v-if="item.materialNo">
                                    {{ getUnitName(item.materialNo) }}
                                </span>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
            <el-form-item label="作业人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择作业" @change="handleChangePerson">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo"></el-option>
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="提前通知时间" prop="advanceTime">
                <el-input type="number" v-model="ruleForm.advanceTime" placeholder="请输入提前多少小时通知">
                    <template slot="append">小时</template>
                </el-input>
            </el-form-item> -->
            <el-form-item label="计划状态" v-if="ruleForm.status !== 'INVALID'">
                <el-switch v-model="ruleForm.status" active-color="#13ce66" inactive-color="#ff4949"
                    :active-value="'ENABLE'" :inactive-value="'DISABLE'" active-text="启用" inactive-text="停用">
                </el-switch>
            </el-form-item>
            <el-form-item label="计划状态" v-else>
                <span>计划失效</span>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import jobTaskTemplate from '@/api/jobManagment/jobTaskTemplate';
let diffInDays = 0;
export default {
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        planList: {
            type: Array,
            default: () => {
                return []
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (Number(value) > 0) { callback() } else {
                callback(new Error('请输入大于0的数值！'))
            }
        };
        let validatorDiffInDays = function (rule, value, callback) {
            console.log(diffInDays)
            if (diffInDays) {
                if (Number(value) > diffInDays) {
                    callback(new Error(`最大天数间隔为${diffInDays}天！`))
                } else if (Number(value) > 0 && Number(value) % 1 == 0) {
                    callback()
                } else {
                    callback(new Error('请输入大于0的整数值！'))
                }
            } else {
                callback(new Error('请先选择计划！'))
            }

        };
        return {
            resetDays: true,
            workTypeList: [
                {
                    name: "换水作业",
                    key: 'CHANGE_WATER'
                },
                {
                    name: "漏网作业",
                    key: 'EXPOSED_NET'
                },
                {
                    name: "消杀作业",
                    key: "DISINFECTION_WATER"
                },
                {
                    name: "饲喂作业",
                    key: 'FEEDING'
                },
                {
                    name: "吊网作业",
                    key: 'HANGING_NET'
                }
            ],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now();
                }
            },
            warningText: '',
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                taskTemplateName: [
                    { required: true, message: '请输入任务模板名称', trigger: 'change' }
                ],
                workPlanId: [
                    { required: true, message: '请选择计划', trigger: 'change' }
                ],
                intervalDay: [
                    { required: true, validator: validatorDiffInDays, trigger: 'change' }
                ],
                generationTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                taskTemplateTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                executionStartDay: [
                    { required: true, message: '请选择开始天', trigger: 'change' }
                ],
                executionStartTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                executionEndDay: [
                    { required: true, message: '请选择结束天', trigger: 'change' }
                ],
                executionEndTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
                workType: [
                    { required: true, message: '请选择作业类型', trigger: 'change' }
                ],
                facilityId: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                materialNo: [
                    { required: true, message: '请选择物料', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择作业人', trigger: 'change' }
                ],
                // advanceTime: [
                //     { required: true, validator: validatorTime, trigger: 'change' }
                // ]
            }
        }
    },

    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        getUnitName(no) {
            let rut = this.materialList.find(item => {
                return item.materialNo == no
            })
            return rut ? rut.unitName : ''
        },
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.ruleForm = {
                    status: 'ENABLE'
                }
                this.addEditApi = jobTaskTemplate.add
                this.addEditName = '添加'
                this.$set(this.ruleForm, 'taskTemplateDetailList', [{
                    materialName: null, num: null, materialNo: null
                }])
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId,
                }
                this.addEditApi = jobTaskTemplate.edit
                this.addEditName = '编辑'
                this.handleChangePlan(this.data.workPlanId);
                this.$set(this.ruleForm, 'generationTime', this.data.generationTime);
                this.$set(this.ruleForm, 'executionEndTime', this.data.executionEndTime);
                this.$set(this.ruleForm, 'executionStartTime', this.data.executionStartTime);
                this.$set(this.ruleForm, 'taskTemplateTime', [this.data.startTime, this.data.endTime]);
                this.$set(this.ruleForm, 'intervalDay', this.data.intervalDay);
                if (this.ruleForm.taskTemplateDetailList && this.ruleForm.taskTemplateDetailList.length == 0) {
                    this.$set(this.ruleForm, 'taskTemplateDetailList', [{
                        materialName: null, num: null, materialNo: null
                    }])
                }
            }
        },
        disableTime(time) {
            if (new Date(time).getTime() > Date.now()) {
                return false
            } else {
                return true
            }
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchName', '');
            this.$set(this.ruleForm, 'batchId', '');
        },
        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
        },
        handleChangeTime(key) {
            let executionStartTime = this.ruleForm.executionStartTime;
            let executionEndTime = this.ruleForm.executionEndTime;
            let executionStartDay = this.ruleForm.executionStartDay;
            let executionEndDay = this.ruleForm.executionEndDay;
            let timeRange = false
            timeRange = this.compareTimes(executionStartTime, executionEndTime)
            if (executionStartDay == executionEndDay && !timeRange && executionEndDay && executionStartDay) {
                if (key == 'executionStartTime') {
                    this.$set(this.ruleForm, 'executionEndTime', '')
                } else if (key == 'executionEndTime') {
                    this.$set(this.ruleForm, 'executionStartTime', '')
                }
                this.$message.warning('执行日为同一天时，执行结束时间需要大于开始时间，请重新选择时间！')
            }
        },
        compareTimes(time1, time2) {
            if (!time1 || !time2) {
                return false
            }
            // 将时间字符串分割为小时和分钟  
            const [h1, m1] = time1.split(':').map(Number);
            const [h2, m2] = time2.split(':').map(Number);

            // 将时间转换为总分钟数  
            const totalMinutes1 = h1 * 60 + m1;
            const totalMinutes2 = h2 * 60 + m2;
            console.log(totalMinutes1, totalMinutes2)
            // 比较总分钟数  
            if (totalMinutes1 < totalMinutes2) {
                return true;
            } else {
                return false;
            }
        },
        handleChangeIntervalDay(days) {
            if (this.ruleForm.executionStartDay > days) {
                this.ruleForm.executionStartDay = '';
            } else if (this.ruleForm.executionEndDay > days) {
                this.ruleForm.executionEndDay = '';
            };
        },
        handleChangePlan(id) {
            let row = this.planList.find(item => item.workPlanId == id);
            console.log(row)
            let endTime = row.endTime;
            this.$set(this.pickerOptions, 'disabledDate', (time) => {
                const endDate = new Date(endTime); // 最晚可选时间  
                return time.getTime() < new Date().getTime() || time.getTime() > endDate.getTime();
            });
            diffInDays = this.getDaysBetweenDates(new Date(), endTime);
            this.warningText = `计划时间范围在当前时间至${endTime}，最大间隔${diffInDays}天。`;
            this.$set(this.ruleForm, 'intervalDay', '');
            this.$set(this.ruleForm, 'workPlanName', row.workPlanName);
            this.$set(this.ruleForm, 'taskTemplateTime', []);
        },
        handChangeDays() {
            if (!this.ruleForm.executionEndDay && !this.ruleForm.executionStartDay) {
                this.$refs.resetDays.resetField();
            }
        },
        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        handleGetMaterialName(no) {
            console.log(no)
            let row = this.materialList.find(item => Number(item.materialNo) == Number(no));
            return row.materialName;
        },
        getDaysBetweenDates(startDateStr, endDateStr) {
            const startDate = new Date(startDateStr);
            const endDate = new Date(endDateStr);

            // 首先，计算两个日期之间的毫秒数差  
            const diffInMilliseconds = endDate - startDate;
            // 将毫秒数差转换为天数，这里我们使用Math.floor来确保只计算完整的天数  
            return Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24));
        },
        addMaterial() {
            let length = this.ruleForm.taskTemplateDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.taskTemplateDetailList, length, {
                    materialName: null, num: null, materialNo: null
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.taskTemplateDetailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'taskTemplateDetailList', list)
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (this.ruleForm.workType !== 'FEEDING') {
                        this.ruleForm.taskTemplateDetailList = []
                    }
                    if (this.ruleForm.taskTemplateDetailList && this.ruleForm.taskTemplateDetailList.length > 0) {
                        this.ruleForm.taskTemplateDetailList.forEach(item => {
                            item.materialName = this.handleGetMaterialName(item.materialNo)
                        })
                    };
                    let params = {
                        startTime: this.ruleForm.taskTemplateTime[0],
                        endTime: this.ruleForm.taskTemplateTime[1]
                    };
                    this.addEditApi({ ...this.ruleForm, ...params }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败';
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg);
                        res.code == 1 && delete this.ruleForm.taskTemplateTime;
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err);
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.warningText = '';
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
        },
        //取消关闭
        cancel() {
            this.resetForm();
            this.$emit("closeDialog");
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); done(); })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item__content {
        margin: 0 !important;
    }

    .el-form-item {
        .label {
            display: none;
        }


    }
}

::v-deep .el-dialog {
    margin-top: 5vh !important;
}

.elRow {
    text-align: center;
}
</style>